package com.gdou.im.server;

import com.gdou.im.server.initializer.WebSocketChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * @ProjectName: demo
 * @Package: com.gdou.im.server
 * @ClassName: NettyServer
 * @Author: carrymaniac
 * @Description: netty的服务器端
 * @Date: 2020/1/4 1:08 下午
 * @Version:
 */
@Slf4j
@Component("nettyServer")
public class NettyServer {
    private final WebSocketChannelInitializer initializer;
    private final NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    private final NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    private Channel channel;

    public NettyServer(WebSocketChannelInitializer initializer) {
        this.initializer = initializer;
    }

    public ChannelFuture bing(InetSocketAddress address) throws InterruptedException {
        //定义线程组
        final ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new ChannelInitializer<NioServerSocketChannel>() {
                    @Override
                    protected void initChannel(NioServerSocketChannel ch) throws Exception {
                        log.info("[NettyServer]Server Start!");
                    }
                })
                .option(ChannelOption.SO_BACKLOG,1024)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(initializer);
        ChannelFuture future = serverBootstrap.bind(address).syncUninterruptibly();
        channel = future.channel();
        return future;
    }

    public void destroy(){
        if(channel==null){
            return;
        }
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
